package com.virtium.vpc.dao.hibernate;

import java.util.List;
import org.hibernate.Session;
import com.virtium.vpc.dao.GenericDAO;
import com.virtium.vpc.dao.HibernateSessionFactory;
import com.virtium.vpc.utils.HibernateUtil;

/**
 * Data access object (DAO) for domain model
 * 
 * @author NguyenTuanAnh
 */
public class BaseHibernateDAO implements GenericDAO {
	protected Class persistentClass = null;
	protected Session hsession = null;

	public BaseHibernateDAO() {

	};

	public Class getPersistentClass() {
		return this.persistentClass;
	}

	public Session getSession() {
		if (this.hsession == null || !this.hsession.isOpen()) {
			this.hsession = HibernateUtil.openSession();
		}
		return this.hsession;
	}

	public void closeSession() {
		if (this.hsession != null) {
			if (this.hsession.isOpen()) {
				System.out.println("**** Closing Hibernate Session ****");
				this.hsession.close();
			} else
				System.out.println("Hibernate Session is closed already...");

			this.hsession = null;
		}
	}

	public Session currentSession(boolean enableFilter) {
		if (this.hsession == null || !this.hsession.isOpen()) {
			this.hsession = HibernateSessionFactory.getSession();
		}
		return this.hsession;
	}

	public List executeQuery(boolean enableFilter, String query) {
		List list = null;

		try {
			list = currentSession(enableFilter).createQuery(query).list();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		return list;

	}

	protected void finalize() {
		System.out.println("Finalize() of class " + this.getClass().getName()
				+ " is called...");
		closeSession();
	}

}